﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextCursor>
#include "globals.h"
#include <QDialog>
#include <QVBoxLayout>
#include "qcustomplot.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , serialPort(new QSerialPort(this))  // 添加这行初始化串口对象
    , isConnected(false)
    , isHexMode(false)                   // 初始化十六进制模式为false
    , serialRingBuffer(nullptr)
{
    ui->setupUi(this);
    serialPortInit();

    // 连接串口数据接收信号
    connect(serialPort, &QSerialPort::readyRead,
            this, &MainWindow::readSerialData);

    // 初始化Hex按钮文字
    ui->pushButton_hexMode->setText("Hex");
    // 创建环形缓冲区
    serialRingBuffer = rngCreate(4096*5);
    if (!serialRingBuffer) {
        ui->textEdit_recv->append("错误：无法创建环形缓冲区！");
    }
}



void MainWindow::readSerialData()
{
    // 读取串口数据
    QByteArray data = serialPort->readAll();

    QString dataStr;
    if (isHexMode) {
        // 十六进制模式：立刻追加原始Hex到显示框
        dataStr = data.toHex(' ').toUpper();
        ui->textEdit_recv->append(dataStr);
        ui->textEdit_recv->moveCursor(QTextCursor::End);
        uint8_t buff[sizeof(NewF_Collectdata)] = {0};
        HEAD_DATA_MESSAGE *rxHead = (HEAD_DATA_MESSAGE *)buff;
        if (serialRingBuffer)
        {
            int bytesWritten = rngBufPut(serialRingBuffer, data.data(), data.size());
            if (bytesWritten < data.size()) {
                ui->textEdit_recv->append("警告：环形缓冲区已满，数据可能丢失！");
                ui->textEdit_recv->append(QString("data.size() = %1").arg(data.size()));
                ui->textEdit_recv->append(QString("bytesWritten = %1").arg(bytesWritten));
            }
        }
        while(1)
        {
            size_t rnglen = rngNBytes(serialRingBuffer);    // 环形缓冲区里的数据长度
            if (rnglen < sizeof(HEAD_DATA_MESSAGE))
            {
                return;
            }

            uint32_t r = rngBufGetNoDel(serialRingBuffer, (char*)buff, sizeof(HEAD_DATA_MESSAGE));
            if (rxHead->head !=0x55444648)  //rxHead->head != TXHead
            {
                //ui->textEdit_recv->append(QString("rxHead->head========%1").arg(rxHead->head));
                rngBufGet(serialRingBuffer, (char*)buff, 1);
                continue;
            }
            //ui->textEdit_recv->append(QString("rxHead->len========%1").arg(rxHead->len));
            if ((rxHead->len) > sizeof(buff))//数据帧大小大于整个接收缓存则错误
            {
                rngBufGet(serialRingBuffer, (char*)buff, 1);
                return;
            }

            if (rxHead->len > (uint32_t)rngNBytes(serialRingBuffer))//数据帧大小大于整个环形缓存则错误
                return;

            r = rngBufGet(serialRingBuffer, (char*)buff, rxHead->len);  //没有错误的话,取整个数据包,大小不够继续接收
            if (r != rxHead->len)
                return;

            if(rxHead->id == 0x11)
            {
                ui->textEdit_recv->append("=== 收到debug数据 ===");
            }
            if(rxHead->id == 101)
            {
                ui->textEdit_recv->append("=== 收到collect数据 ===");
                Collect_data=(NewF_Collectdata *)buff;
                ui->textEdit_recv->append(QString("head=%1").arg(Collect_data->head));
                ui->textEdit_recv->append(QString("id=%1").arg(Collect_data->id));
                ui->textEdit_recv->append(QString("len=%1").arg(Collect_data->len));
                ui->textEdit_recv->append(QString("freq=%1").arg(Collect_data->freq));
                ui->textEdit_recv->append(QString("taskId=%1").arg(Collect_data->taskId));
                ui->textEdit_recv->append(QString("tail=%1").arg(Collect_data->tail));
                //qDebug() << "sizeof(NewF_Collect_Message)=" << sizeof(NewF_Collectdata);
                // 打印全部 4096 字节（可能很长）
                qDebug().noquote() << "E901:" << QByteArray(reinterpret_cast<const char*>(Collect_data->E901), sizeof(Collect_data->E901)).toHex(' ');
                qDebug().noquote() << "E895:" << QByteArray(reinterpret_cast<const char*>(Collect_data->E895), sizeof(Collect_data->E895)).toHex(' ');
                // 实时更新图表，仅显示 E895
                if (echartsPlot) {
                    const int N = 4096;
                    QVector<double> x(N), y(N);
                    for (int i = 0; i < N; ++i) { x[i] = i; y[i] = Collect_data->E895[i]; }
                    if (echartsPlot->graphCount() < 1) {
                        echartsPlot->clearGraphs();
                        echartsPlot->addGraph();
                        echartsPlot->graph(0)->setPen(QPen(Qt::red));
                        echartsPlot->xAxis->setLabel("Index");
                        echartsPlot->yAxis->setLabel("E895");
                        echartsPlot->xAxis->setRange(0, N-1);
                        echartsPlot->yAxis->setRange(50, 255);
                        echartsPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
                    }
                    echartsPlot->graph(0)->setData(x, y);
                    echartsPlot->replot(QCustomPlot::rpQueuedReplot);
                }
                if (echartsPlot2) {
                    const int N = 4096;
                    QVector<double> x2(N), y2(N);
                    for (int i = 0; i < N; ++i) { x2[i] = i; y2[i] = Collect_data->E901[i]; }
                    if (echartsPlot2->graphCount() < 1) {
                        echartsPlot2->clearGraphs();
                        echartsPlot2->addGraph();
                        echartsPlot2->graph(0)->setPen(QPen(Qt::blue));
                        echartsPlot2->xAxis->setLabel("Index");
                        echartsPlot2->yAxis->setLabel("E901");
                        echartsPlot2->xAxis->setRange(0, N-1);
                        echartsPlot2->yAxis->setRange(50, 255);
                        echartsPlot2->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
                    }
                    echartsPlot2->graph(0)->setData(x2, y2);
                    echartsPlot2->replot(QCustomPlot::rpQueuedReplot);
                }
                return;
            }
        }

    } else {
        // 文本模式：将数据转换为字符串并显示
        dataStr = QString::fromUtf8(data);
        ui->textEdit_recv->append(dataStr);
        ui->textEdit_recv->moveCursor(QTextCursor::End);
    }
}

void MainWindow::serialPortInit()
{
    // 获取可用串口
    QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
    ui->comboBox_serialPort->clear();

    for (const QSerialPortInfo &port : ports) {
        QString portName = port.portName();
        // 在循环内添加项目
        QString displayText = QString("%1").arg(portName);
        ui->comboBox_serialPort->addItem(displayText, portName);
    }

    ui->comboBox_baudRate->clear();
    ui->comboBox_baudRate->addItem("115200", 115200);
    ui->comboBox_baudRate->addItem("38400", 38400);
    ui->comboBox_baudRate->addItem("9600", 9600);
    // 设置默认选择115200
    ui->comboBox_baudRate->setCurrentIndex(0);
}




MainWindow::~MainWindow()
{
    if (serialPort && serialPort->isOpen()) {
        serialPort->close();
    }
    // 释放环形缓冲区
    if (serialRingBuffer) {
        rngDelete(serialRingBuffer);
        serialRingBuffer = nullptr;
    }
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    serialPortInit();
}

// 连接按钮点击处理函数
void MainWindow::on_pushButton_connect_clicked()
{
    if (!isConnected) {
        // 连接串口
        QString portName = ui->comboBox_serialPort->currentData().toString();
        int baudRate = ui->comboBox_baudRate->currentData().toInt();

        if (portName.isEmpty()) {
            QMessageBox::warning(this, "警告", "请选择串口");
            return;
        }

        // 设置串口参数
        serialPort->setPortName(portName);
        serialPort->setBaudRate(baudRate);
        serialPort->setDataBits(QSerialPort::Data8);
        serialPort->setParity(QSerialPort::NoParity);
        serialPort->setStopBits(QSerialPort::OneStop);
        serialPort->setFlowControl(QSerialPort::NoFlowControl);

        // 打开串口
        if (serialPort->open(QIODevice::ReadWrite)) {
            isConnected = true;
            ui->pushButton_connect->setText("断开");
            ui->comboBox_serialPort->setEnabled(false);
            ui->comboBox_baudRate->setEnabled(false);

            //QMessageBox::information(this, "成功", "串口连接成功");
        } else {
            QMessageBox::critical(this, "错误",
                QString("串口连接失败：%1").arg(serialPort->errorString()));
        }
    } else {
        // 断开串口
        serialPort->close();
        isConnected = false;
        ui->pushButton_connect->setText("连接");
        ui->comboBox_serialPort->setEnabled(true);
        ui->comboBox_baudRate->setEnabled(true);

        //QMessageBox::information(this, "信息", "串口已断开！");
    }
}

// 十六进制模式切换按钮点击处理函数
void MainWindow::on_pushButton_hexMode_clicked()
{
    // 切换十六进制模式状态
    isHexMode = !isHexMode;

    // 更新按钮文字
    if (isHexMode) {
        ui->pushButton_hexMode->setText("Str");
    } else {
        ui->pushButton_hexMode->setText("Hex");
    }

    // 可选：清空当前显示内容，重新显示（如果需要的话）
    // ui->textEdit_recv->clear();
}

void MainWindow::on_pushButton_clear_clicked()
{
    // 清空接收数据显示文本框
    ui->textEdit_recv->clear();
}

void MainWindow::on_pushButton_set_freq_clicked()
{
    Collect_Msg.head=0x55444648;
    Collect_Msg.id=0;
    Collect_Msg.len=sizeof(Collect_Msg);
	{
		QString t = ui->lineEdit_setfreq->text().trimmed();
		bool ok = false;
		uint32_t v = static_cast<uint32_t>(t.toUInt(&ok));
		Collect_Msg.data0 = ok ? v : 2450;
	}
    Collect_Msg.data1=100;
    Collect_Msg.data2=ui->comboBox_set_freq->currentText().toInt();
    Collect_Msg.tail=0x55444645;
    if (isConnected && serialPort->isOpen()) {
    QByteArray out(reinterpret_cast<const char*>(&Collect_Msg), sizeof(Collect_Msg));
        serialPort->write(out);
    } else {
        QMessageBox::warning(this, "警告", "串口未连接");
    }
    ui->pushButton_set_freq->setStyleSheet("background-color:#4CAF50; color:white;");
}




void MainWindow::on_pushButton_set_mode_clicked()
{
    Collect_Msg.head=0x55444648;
    Collect_Msg.id=1;
    Collect_Msg.len=sizeof(Collect_Msg);
    Collect_Msg.data0=ui->comboBox_set_mode->currentText().toInt();
    Collect_Msg.data1=0;
    Collect_Msg.data2=0;
    Collect_Msg.tail=0x55444645;
    if (isConnected && serialPort->isOpen()) {
    QByteArray out(reinterpret_cast<const char*>(&Collect_Msg), sizeof(Collect_Msg));
        serialPort->write(out);
    } else {
        QMessageBox::warning(this, "警告", "串口未连接");
    }
    if(ui->comboBox_set_mode->currentText().toInt()==0)
    {
        ui->pushButton_set_mode->setStyleSheet("");
        ui->pushButton_set_freq->setStyleSheet("");
    }
    else
    {
        ui->pushButton_set_mode->setStyleSheet("background-color:#4CAF50; color:white;");
    }

}

void MainWindow::on_pushButton_echarts_clicked()
{
    if (!echartsDialog) {
        echartsDialog = new QDialog(this);
        echartsDialog->setAttribute(Qt::WA_DeleteOnClose, true);
        echartsDialog->setWindowTitle("Echarts (E895↑ / E901↓)");
        echartsDialog->resize(1400, 700);

        QVBoxLayout *layout = new QVBoxLayout(echartsDialog);
        layout->setContentsMargins(8, 8, 8, 8);
        layout->setSpacing(8);

        // 上：E895
        echartsPlot = new QCustomPlot(echartsDialog);
        layout->addWidget(echartsPlot, 1);
        echartsPlot->addGraph();
        echartsPlot->graph(0)->setPen(QPen(Qt::red));
        echartsPlot->xAxis->setLabel("Index");
        echartsPlot->yAxis->setLabel("E895");
        echartsPlot->xAxis->setRange(0, 4095);
        echartsPlot->yAxis->setRange(50, 255);
        echartsPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

        // 下：E901
        echartsPlot2 = new QCustomPlot(echartsDialog);
        layout->addWidget(echartsPlot2, 1);
        echartsPlot2->addGraph();
        echartsPlot2->graph(0)->setPen(QPen(Qt::blue));
        echartsPlot2->xAxis->setLabel("Index");
        echartsPlot2->yAxis->setLabel("E901");
        echartsPlot2->xAxis->setRange(0, 4095);
        echartsPlot2->yAxis->setRange(50, 255);
        echartsPlot2->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

        connect(echartsDialog, &QObject::destroyed, this, [this]() {
            echartsDialog = nullptr;
            echartsPlot = nullptr;
            echartsPlot2 = nullptr;
        });
    }

    echartsDialog->show();
    echartsDialog->raise();
    echartsDialog->activateWindow();




}

void MainWindow::on_pushButton_setstatus_clicked()
{
    AGILE_HEAD agile_send;
    // 默认按十六进制解析（不写0x也当作十六进制），确保你输入如 C0/10/11/10
    auto readHexByte = [](const QString &s) -> uint8_t {
        bool ok = false;
        unsigned int v = s.trimmed().toUInt(&ok, 16); // 以16进制解析
        return static_cast<uint8_t>(ok ? qBound(0u, v, 255u) : 0u);
    };

    agile_send.headAndId = readHexByte(ui->lineEdit_aligetext1->text()); // C0
    agile_send.cmd       = readHexByte(ui->lineEdit_aligetext2->text()); // 10
    agile_send.data0     = readHexByte(ui->lineEdit_aligetext3->text()); // 11
    agile_send.data1     = readHexByte(ui->lineEdit_aligetext4->text()); // 10
    // agile_send.data2 默认为 0，如需要可再加一个输入框解析

    qDebug().noquote() << "AGILE bytes:" << QByteArray(reinterpret_cast<const char*>(&agile_send), sizeof(agile_send)).toHex(' ').toUpper();
    qDebug() << "AGILE fields:"
             << "headAndId=" << Qt::hex << showbase << agile_send.headAndId
             << "cmd=" << agile_send.cmd
             << "data0=" << agile_send.data0
             << "data1=" << agile_send.data1
             << "data2=" << agile_send.data2;
    if (isConnected && serialPort->isOpen()) {
    QByteArray out(reinterpret_cast<const char*>(&agile_send), sizeof(agile_send));
        serialPort->write(out);
    } else {
        QMessageBox::warning(this, "警告", "串口未连接");
    }
}






void MainWindow::on_pushButton_checkstatus_clicked()
{
    AGILE_HEAD agile_send ;
    agile_send.headAndId=0xC0;
    agile_send.cmd=0x11;
    if (isConnected && serialPort->isOpen()) {
    QByteArray out(reinterpret_cast<const char*>(&agile_send), sizeof(agile_send));
        serialPort->write(out);
    } else {
        QMessageBox::warning(this, "警告", "串口未连接");
    }
}

















